<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="/blog/lib/pace/pace-theme-minimal.min.css">
  <script src="/blog/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/blog/","scheme":"Gemini","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="同步&#x2F;异步 &amp; 阻塞&#x2F;非阻塞">
<meta property="og:type" content="article">
<meta property="og:title" content="同步&#x2F;异步 &amp; 阻塞&#x2F;非阻塞">
<meta property="og:url" content="https://gitee.com/lzx411559669/2020/03/02/%E5%90%8C%E6%AD%A5_%E5%BC%82%E6%AD%A5%20&%20%E9%98%BB%E5%A1%9E_%E9%9D%9E%E9%98%BB%E5%A1%9E/index.html">
<meta property="og:site_name" content="刘正星的博客">
<meta property="og:description" content="同步&#x2F;异步 &amp; 阻塞&#x2F;非阻塞">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.nlark.com/yuque/0/2020/jpeg/316618/1580971873671-4aa37220-f932-4622-8b8a-34fcbb3636a8.jpeg#align=left&display=inline&height=308&originHeight=308&originWidth=685&size=0&status=done&style=none&width=685">
<meta property="og:image" content="https://cdn.nlark.com/yuque/0/2020/png/316618/1581073458578-3e597891-f113-4cff-8bee-cf5da0ccf4a2.png#align=left&display=inline&height=469&originHeight=469&originWidth=608&size=0&status=done&style=none&width=608">
<meta property="og:image" content="https://cdn.nlark.com/yuque/0/2020/png/316618/1581073458593-989e96c5-378d-4639-a199-4a44c13a5bc7.png#align=left&display=inline&height=469&originHeight=469&originWidth=608&size=0&status=done&style=none&width=608">
<meta property="article:published_time" content="2020-03-02T04:10:17.000Z">
<meta property="article:modified_time" content="2020-03-04T14:11:03.626Z">
<meta property="article:author" content="刘正星">
<meta property="article:tag" content="-同步 -异步 -阻塞 -非阻塞">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.nlark.com/yuque/0/2020/jpeg/316618/1580971873671-4aa37220-f932-4622-8b8a-34fcbb3636a8.jpeg#align=left&display=inline&height=308&originHeight=308&originWidth=685&size=0&status=done&style=none&width=685">

<link rel="canonical" href="https://gitee.com/lzx411559669/2020/03/02/%E5%90%8C%E6%AD%A5_%E5%BC%82%E6%AD%A5%20&%20%E9%98%BB%E5%A1%9E_%E9%9D%9E%E9%98%BB%E5%A1%9E/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>同步/异步 & 阻塞/非阻塞 | 刘正星的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/blog/atom.xml" title="刘正星的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
<a href="https://github.com/lzx411559669" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">刘正星的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">欢迎！</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lzx411559669/2020/03/02/%E5%90%8C%E6%AD%A5_%E5%BC%82%E6%AD%A5%20&%20%E9%98%BB%E5%A1%9E_%E9%9D%9E%E9%98%BB%E5%A1%9E/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/uploads/me.jpg">
      <meta itemprop="name" content="刘正星">
      <meta itemprop="description" content="一名不知名的小菜鸡">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="刘正星的博客">
    </span>
      <header class="post-header">
         
        <h1 class="post-title" itemprop="name headline">
          同步/异步 & 阻塞/非阻塞
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-03-02 12:10:17" itemprop="dateCreated datePublished" datetime="2020-03-02T12:10:17+08:00">2020-03-02</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-03-04 22:11:03" itemprop="dateModified" datetime="2020-03-04T22:11:03+08:00">2020-03-04</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/%E7%9F%A5%E8%AF%86%E7%82%B9/" itemprop="url" rel="index"><span itemprop="name">知识点</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>3.6k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>3 分钟</span>
            </span>
            <div class="post-description">同步/异步 & 阻塞/非阻塞</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <meta name="referrer" content="no-referrer"/>
# 同步/异步 &amp; 阻塞/非阻塞

<p><a name="HQsFJ"></a></p>
<h1 id="参考：阻塞和非阻塞，同步和异步博客"><a href="#参考：阻塞和非阻塞，同步和异步博客" class="headerlink" title="参考：阻塞和非阻塞，同步和异步博客"></a><a href="https://www.cnblogs.com/George1994/p/6702084.html" target="_blank" rel="noopener">参考：阻塞和非阻塞，同步和异步博客</a></h1><p><a name="6GC7m"></a></p>
<h1 id="同步、异步有什么区别"><a href="#同步、异步有什么区别" class="headerlink" title="同步、异步有什么区别"></a>同步、异步有什么区别</h1><p>在进行网络编程时，我们通常会看到同步、异步、阻塞、非阻塞四种调用方式以及他们的组合。</p>
<p>其中同步方式、异步方式主要是由客户端（client）控制的，具体如下：</p>
<p><a name="HXMdQ"></a></p>
<h3 id="同步（Sync）"><a href="#同步（Sync）" class="headerlink" title="同步（Sync）"></a>同步（Sync）</h3><p>所谓同步，就是发出一个功能调用时，在没有得到结果之前，该调用就不返回或继续执行后续操作。<br />根据这个定义，Java中所有方法都是同步调用，应为必须要等到结果后才会继续执行。我们在说同步、异步的时候，一般而言是特指那些需要其他端协作或者需要一定时间完成的任务。<br />简单来说，同步就是必须一件一件事做，等前一件做完了才能做下一件事。</p>
<p>例如：B/S模式中的表单提交，具体过程是：客户端提交请求-&gt;等待服务器处理-&gt;处理完毕返回，在这个过程中客户端（浏览器）不能做其他事。</p>
<p><a name="CPkUk"></a></p>
<h3 id="异步（Async）"><a href="#异步（Async）" class="headerlink" title="异步（Async）"></a>异步（Async）</h3><p>异步与同步相对，当一个异步过程调用发出后，调用者在没有得到结果之前，就可以继续执行后续操作。当这个调用完成后，一般通过状态、通知和回调来通知调用者。对于异步调用，调用的返回并不受调用者控制。<br />对于通知调用者的三种方式，具体如下：</p>
<p><strong>状态</strong><br />即监听被调用者的状态（轮询），调用者需要每隔一定时间检查一次，效率会很低。</p>
<p><strong>通知</strong><br />当被调用者执行完成后，发出通知告知调用者，无需消耗太多性能。</p>
<p><strong>回调</strong><br />与通知类似，当被调用者执行完成后，会调用调用者提供的回调函数。</p>
<p>例如：B/S模式中的ajax请求，具体过程是：客户端发出ajax请求-&gt;服务端处理-&gt;处理完毕执行客户端回调，在客户端（浏览器）发出请求后，仍然可以做其他的事。</p>
<p>总结来说，同步和异步的区别：请求发出后，是否需要等待结果，才能继续执行其他操作。</p>
<p>图片实例：<br /><img src="https://cdn.nlark.com/yuque/0/2020/jpeg/316618/1580971873671-4aa37220-f932-4622-8b8a-34fcbb3636a8.jpeg#align=left&display=inline&height=308&originHeight=308&originWidth=685&size=0&status=done&style=none&width=685" alt=""></p>
<p><strong>举个🌰子：</strong><br />比如我们去购物，如果你去商场实体店买一台空调，当你到了商场看中了一款空调，你就想售货员下单。售货员去仓库帮你调配物品。这天你热的实在不行了。就催着商家赶紧给你配送，于是你就等在商场里，候着他们，直到商家把你和空调一起送回家，一次愉快的购物就结束了。<strong>这就是同步调用。</strong><br />　　不过，如果我们赶时髦，就坐再家里打开电脑，在网上订购了一台空调。当你完成网上支付的时候，对你来说购物过程已经结束了。虽然空调还没有送到家，但是你的任务都已经完成了。商家接到你的订单后，就会加紧安排送货，当然这一切已经跟你无关了，你已经支付完成，想什么就能去干什么了，出去溜达几圈都不成问题。等送货上门的时候，接到商家电话，回家一趟签收即可。<strong>这就是异步调用。</strong><br />**<br><a name="NiCZc"></a></p>
<h1 id="阻塞与非阻塞"><a href="#阻塞与非阻塞" class="headerlink" title="阻塞与非阻塞"></a>阻塞与非阻塞</h1><p><strong>一、概念</strong><br />异步：某个事情需要10s完成。而我只需要调用某个函数告诉xxx来帮我做（然后我再干其他的事情）<br />同步：某个事情需要10s完成，我需要一直等它完成（等10s），再能继续后面的工作。<br />阻塞：做某件事情，直到完成，除非超时<br />非阻塞：尝试做，如果不能做，就不做（直接返回），如果能做，就做。<br />前两者和后两者不容易区分，不过前两者更多的有涉及到多线程交互（消息）的场景。<br /><strong>二、举个例子</strong><br />小李喝了想喝水，于是去煮开水。<br />1、小李把水壶放到炉子上，等待水烧开。（同步阻塞）<br />小李感觉这样太费时间。<br />2、小李把水壶放到炉子上，去客厅看电视，时不时去厨房看看水开没有。（同步非阻塞）<br />小李还是觉得自己这样太累，于是买了把会响笛的那种水壶。水开之后，能发出声音。<br />3、小李把响水壶放到炉子上，等待水壶发出声音。（异步阻塞）<br />觉得这样傻等意义不大<br />5、小李把响水壶放到炉子上，去客厅看电视，水壶响之前不再去看它了，响了再去拿壶。（异步非阻塞）<br />这样真好。<br /><strong>三、深入理解</strong><br />阻塞就是 recv/read的时候 socket接收缓冲区要是有数据就读， 没数据我就一直睡觉赖着不走，直到有数据来了读完我才走。send/write的时候，要是发送缓冲区满了，没有空间继续发送了我也一直睡觉赖着不走，直到发送缓冲区腾出足够的空间让我把数据全部塞到发送缓冲区里我才走。（当然如果你通过setsockopt设置了读写超时，超时时间到了还是会返回-1和EAGAIN，不再睡觉等待）<br />非阻塞就是recv/read的时候，要是接收缓冲区有数据我就读完，没有数据我直接带着返回的-1和EGAIN走人，绝不睡觉等待耽误时间。write/send的时候， 要是发送缓冲区有足够的空间，就立刻把数据塞到发送缓冲区去，然后走人，如果发送缓存区满了，空间不足，那直接带着返回的-1和EAGAIN走人。<br />至于IO多路复用，首先要理解的是，操作系统为你提供了一个功能，当你的某个socket接收缓存区有数据可读，或者发送缓冲区有空间可写的时候，它可以给你一个通知。这样当配合非阻塞的socket使用时，只有当系统通知我哪个描述符可读了，我才去执行read操作，可以保证每次read都能读到有效数据而不做纯返回-1和EAGAIN的无用功。写操作类似。操作系统的这个功能通过select/poll/epoll之类的系统调用函数来使用，这些函数都可以同时监视多个描述符的读写就绪状况，这样，多个描述符的I/O操作都能在一个线程内完成，这就叫I/O多路复用，这里的“复用”指的是复用同一个线程。<br />至于事件驱动，其实是I/O多路复用的一个另外的称呼。</p>
<p><a name="nqeUu"></a></p>
<h1 id="完全理解参考：同步-异步与阻塞-非阻塞——知乎"><a href="#完全理解参考：同步-异步与阻塞-非阻塞——知乎" class="headerlink" title="完全理解参考：同步/异步与阻塞/非阻塞——知乎"></a>完全理解<a href="https://zhuanlan.zhihu.com/p/22707398" target="_blank" rel="noopener">参考：同步/异步与阻塞/非阻塞——知乎</a></h1><p>随便翻开一本Node.js入门书籍的绪论部分，一般都可以看到「异步」、「单线程」、「非阻塞」这样的字眼。因其采用异步非阻塞的模型而构建，Node.js得以能充分利用CPU资源，具有极强的处理高并发请求的能力。<br />可是到底什么是同步和异步？什么是阻塞和非阻塞？同步就意味着阻塞吗？异步就一定是非阻塞吗？即便是业务经验十分丰富的Node.js程序员，都不一定对这些概念辨别得十分明晰。<br />本文力求以简明的语言来解释清楚这几个概念并加以区分，但不涉及到Node.js底层的具体实现。<br><a name="n4cWa"></a></p>
<h3 id="阻塞和非阻塞"><a href="#阻塞和非阻塞" class="headerlink" title="阻塞和非阻塞"></a>阻塞和非阻塞</h3><p>从简单的开始，我们以经典的读取文件的模型举例。（对操作系统而言，所有的输入输出设备都被抽象成文件。）<br />在发起读取文件的请求时，应用层会调用系统内核的I/O接口。<br />如果应用层调用的是阻塞型I/O，那么在调用之后，应用层即刻被挂起，一直出于等待数据返回的状态，直到系统内核从磁盘读取完数据并返回给应用层，应用层才用获得的数据进行接下来的其他操作。<br />如果应用层调用的是非阻塞I/O，那么调用后，系统内核会立即返回（虽然还没有文件内容的数据），应用层并不会被挂起，它可以做其他任意它想做的操作。（至于文件内容数据如何返回给应用层，这已经超出了阻塞和非阻塞的辨别范畴。）<br />这便是（脱离同步和异步来说之后）阻塞和非阻塞的区别。总结来说，是否是阻塞还是非阻塞，关注的是接口调用（发出请求）后等待数据返回时的状态。被挂起无法执行其他操作的则是阻塞型的，可以被立即「抽离」去完成其他「任务」的则是非阻塞型的。<br /><img src="https://cdn.nlark.com/yuque/0/2020/png/316618/1581073458578-3e597891-f113-4cff-8bee-cf5da0ccf4a2.png#align=left&display=inline&height=469&originHeight=469&originWidth=608&size=0&status=done&style=none&width=608" alt=""><br><a name="UVgTj"></a></p>
<h3 id="同步和异步"><a href="#同步和异步" class="headerlink" title="同步和异步"></a>同步和异步</h3><p>阻塞和非阻塞解决了应用层等待数据返回时的状态问题，那系统内核获取到的数据到底如何返回给应用层呢？这里不同类型的操作便体现的是同步和异步的区别。<br />对于同步型的调用，应用层需要自己去向系统内核问询，如果数据还未读取完毕，那此时读取文件的任务还未完成，应用层根据其阻塞和非阻塞的划分，或挂起或去做其他事情（所以同步和异步并不决定其等待数据返回时的状态）；如果数据已经读取完毕，那此时系统内核将数据返回给应用层，应用层即可以用取得的数据做其他相关的事情。<br />而对于异步型的调用，应用层无需主动向系统内核问询，在系统内核读取完文件数据之后，会主动通知应用层数据已经读取完毕，此时应用层即可以接收系统内核返回过来的数据，再做其他事情。<br />这便是（脱离阻塞和非阻塞来说之后）同步和异步的区别。也就是说，是否是同步还是异步，关注的是任务完成时消息通知的方式。由调用方盲目主动问询的方式是同步调用，由被调用方主动通知调用方任务已完成的方式是异步调用。<br /><img src="https://cdn.nlark.com/yuque/0/2020/png/316618/1581073458593-989e96c5-378d-4639-a199-4a44c13a5bc7.png#align=left&display=inline&height=469&originHeight=469&originWidth=608&size=0&status=done&style=none&width=608" alt=""><br><a name="juxx3"></a></p>
<h3 id="场景举例与总结"><a href="#场景举例与总结" class="headerlink" title="场景举例与总结"></a>场景举例与总结</h3><p>最后，再来举一个我们日常的例子来加深对这几个概念的理解。<br />假设小明需要在网上下载一个软件：</p>
<ul>
<li>如果小明点击下载按钮之后，就一直干瞪着进度条不做其他任何事情直到软件下载完成，这是同步阻塞；</li>
<li>如果小明点击下载按钮之后，就一直干瞪着进度条不做其他任何事情直到软件下载完成，但是软件下载完成其实是会「叮」的一声通知的（但小明依然那样干等着），这是异步阻塞；（不常见）</li>
<li>如果小明点击下载按钮之后，就去做其他事情了，不过他总需要时不时瞄一眼屏幕看软件是不是下载完成了，这是同步非阻塞；</li>
<li>如果小明点击下载按钮之后，就去做其他事情了，软件下载完之后「叮」的一声通知小明，小明再回来继续处理下载完的软件，这是异步非阻塞。</li>
</ul>
<p>相信看完以上这个案例之后，这几个概念已经能够分辨得很清楚了。<br />总的来说，同步和异步关注的是任务完成消息通知的机制，而阻塞和非阻塞关注的是等待任务完成时请求者的状态。</p>

    </div>

    
    
    
        <div class="reward-container">
  <div></div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blog/uploads/vx.png" alt="刘正星 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/blog/uploads/alipay.jpg" alt="刘正星 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

            <div class="social-item">
              <a target="_blank" class="social-link" href="/atom.xml">
                <span class="icon">
                  <i class="fa fa-rss"></i>
                </span>

                <span class="label">RSS</span>
              </a>
            </div>
    </div>
  </div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/blog/tags/%E5%90%8C%E6%AD%A5-%E5%BC%82%E6%AD%A5-%E9%98%BB%E5%A1%9E-%E9%9D%9E%E9%98%BB%E5%A1%9E/" rel="tag"><i class="fa fa-tag"></i> -同步 -异步 -阻塞 -非阻塞</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2019/04/14/%E5%A4%96%E8%BE%B9%E8%B7%9D%E5%90%88%E5%B9%B6%E9%97%AE%E9%A2%98/" rel="prev" title="外边距合并问题">
      <i class="fa fa-chevron-left"></i> 外边距合并问题
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2020/03/02/%E5%AD%A6%E4%B9%A0Markdown/" rel="next" title="学习Markdown">
      学习Markdown <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  
   <div>
      
        ﻿
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/blog/2020/03/02/%E5%90%8C%E6%AD%A5_%E5%BC%82%E6%AD%A5%20&%20%E9%98%BB%E5%A1%9E_%E9%9D%9E%E9%98%BB%E5%A1%9E/">同步/异步 & 阻塞/非阻塞</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 刘正星 的个人博客">刘正星</a></p>
  <p><span>发布时间:</span>2020年03月02日 - 12:03</p>
  <p><span>最后更新:</span>2020年03月04日 - 22:03</p>
  <p><span>原始链接:</span><a href="/blog/2020/03/02/%E5%90%8C%E6%AD%A5_%E5%BC%82%E6%AD%A5%20&%20%E9%98%BB%E5%A1%9E_%E9%9D%9E%E9%98%BB%E5%A1%9E/" title="同步/异步 & 阻塞/非阻塞">https://gitee.com/lzx411559669/2020/03/02/%E5%90%8C%E6%AD%A5_%E5%BC%82%E6%AD%A5%20&%20%E9%98%BB%E5%A1%9E_%E9%9D%9E%E9%98%BB%E5%A1%9E/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://gitee.com/lzx411559669/2020/03/02/%E5%90%8C%E6%AD%A5_%E5%BC%82%E6%AD%A5%20&%20%E9%98%BB%E5%A1%9E_%E9%9D%9E%E9%98%BB%E5%A1%9E/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>

      
   </div>
  </div>


          </div>
          
    
  <div class="comments">
    <div id="lv-container" data-id="city" data-uid="MTAyMC80ODg4Ny8yNTM4MQ=="></div>
  </div>
  

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#参考：阻塞和非阻塞，同步和异步博客"><span class="nav-number">1.</span> <span class="nav-text">参考：阻塞和非阻塞，同步和异步博客</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#同步、异步有什么区别"><span class="nav-number">2.</span> <span class="nav-text">同步、异步有什么区别</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#同步（Sync）"><span class="nav-number">2.0.1.</span> <span class="nav-text">同步（Sync）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#异步（Async）"><span class="nav-number">2.0.2.</span> <span class="nav-text">异步（Async）</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#阻塞与非阻塞"><span class="nav-number">3.</span> <span class="nav-text">阻塞与非阻塞</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#完全理解参考：同步-异步与阻塞-非阻塞——知乎"><span class="nav-number">4.</span> <span class="nav-text">完全理解参考：同步&#x2F;异步与阻塞&#x2F;非阻塞——知乎</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#阻塞和非阻塞"><span class="nav-number">4.0.1.</span> <span class="nav-text">阻塞和非阻塞</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#同步和异步"><span class="nav-number">4.0.2.</span> <span class="nav-text">同步和异步</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#场景举例与总结"><span class="nav-number">4.0.3.</span> <span class="nav-text">场景举例与总结</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="刘正星"
      src="/blog/uploads/me.jpg">
  <p class="site-author-name" itemprop="name">刘正星</p>
  <div class="site-description" itemprop="description">一名不知名的小菜鸡</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">6</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://gitee.com/lzx411559669" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;lzx411559669"><i class="fa fa-fw fa-gitee"></i>Gitee</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://github.com/lzx411559669" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;lzx411559669" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/blog/411559669@qq.com" title="E-Mail → 411559669@qq.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="http://wpa.qq.com/msgrd?v=3&uin=411559669&site=qq&menu=yes" title="QQ → http:&#x2F;&#x2F;wpa.qq.com&#x2F;msgrd?v&#x3D;3&amp;uin&#x3D;411559669&amp;site&#x3D;qq&amp;menu&#x3D;yes" rel="noopener" target="_blank"><i class="fa fa-fw fa-qq"></i>QQ</a>
      </span>
  </div>



      </div>

     <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=471565537&auto=0&height=66"></iframe>

<!--
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=220 src="//music.163.com/outchain/player?type=0&id=4894835465&auto=0&height=430"></iframe>
-->
<iframe scrolling="no" src="https://tianqiapi.com/api.php?style=tx&skin=sogou" frameborder="0" width="100%" height="50" allowtransparency="true"></iframe>
    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">刘正星</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">39k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">35 分钟</span>
</div>
<!--
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.2.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.7.2
  </div>
-->

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<!--
<div class="powered-by">
  <i class="fa fa-user-md"></i>
  <span id="busuanzi_container_site_pv">
    本站访问量:<span id="busuanzi_value_site_pv"></span>次
  </span>
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_container_site_uv">
    本站总访客量：<span id="busuanzi_value_site_uv"></span>人
  </span>
</div>
  <span class="post-meta-divider">|</span>
<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共16.2k字</span>
</div>

-->

<span id="busuanzi_container_site_pv" > 总访问量 <span id="busuanzi_value_site_pv"></span> 次 </span>
<span id="busuanzi_container_site_uv" >| 总访客数 <span id="busuanzi_value_site_uv"></span> 人 </span>
<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">| 博客全站共16.2k字</span>
</div>


        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>













  

  

<script>
NexT.utils.loadComments(document.querySelector('#lv-container'), () => {
  window.livereOptions = {
    refer: location.pathname.replace(CONFIG.root, '').replace('index.html', '')
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
});
</script>

</body>
</html>
<!-- ��̬���� -->
<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
<!-- ҳ����С���� -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>